<?php
class Section {
	static function validate($db="",$isEdit=false) {
		if($db)$db=DB::$db;
		$res['state'] = true;
		$res['error'] = array();

		$p = $_POST;
		if(!isset($p)) {
			$res['state'] = false;
			return $res;
		}
		if(!(isset($p["name"]) && !empty($p["name"]) && strlen(utf8_decode($p["name"])) > 2 && strlen(utf8_decode($p["name"])) < 100)) {
			$res['state'] = false;
			$res['error']['name'] = 1;
		}else if(!$isEdit){
			$a = DB::query("select name from `section` where name='" . $p['name'] . "'");
			if(!empty($a)) {
				$res['state'] = false;
				$res['error']['name'] = 1;
			}
		}
		return $res;
	}
	
	static function get($db="",$name="",$id=-1,$where="",$field="*"){
		if($db=="")$db=DB::$db;
		$sql = "select ".$field." from `section`";
		if($where!=""){
			$where=" where ".$where;
		}else if($name!=""){
			$where=" where `name`='".$name."'";
		}else if($id>0){
			$where=" where `id`='".$id."'";
		}
		if(User::checkAccess('developer')){
			$where=$where;
		}else{
			$where = $where!=""?$where." and ":" where";
			$where.= "`state`=0";
		}
		return DB::query($sql.$where);
	}
	
	static function set($db="",$data,$name="",$id=-1){
		$sql = "update `section` set";
		$where = " where ";
		$comma = "";
		if(($name==""&&$id<0)||empty($data))return false;
		if($name!=""){
			$where.="`name`='".$name."'";
		}else if($id>0){
			$where.="`id`='".$id."'";
		}
		foreach ($data as $key => $value) {
			$val = trim($value);
			$sql.= $comma."`".$key."`='".$val."'";
			$comma=",";
		}
		DB::exec_($sql.$where);
		
		return true;
	}
	
	static function delete($id){
		DB::exec_("delete from `section` where `id`='".$id."'");
	}

	static function create($db) {
		if(!User::checkAccess('admin'))	die('Ошибка доступа!!!');
		$p = $_POST;
		foreach($p as $key => $value) {
			if(is_string($value)){
				$p[$key] = trim($value);
			}
		}

		$db -> query("insert into `section` (`name`,`author`,`descr`) values ('" . $p['name'] . "','" . $_SESSION['user']['person']['id'] . "','')");
		
		$section = Section::get($db,$p['name']);
		$id 	 = isset($section[0])&&isset($section[0]['id'])?$section[0]['id']:-1;
		if($id>=0){
			$res = array("state" => true, "msg" => "Создание новой секции выполнено!");
		}else{
			$res = array("state" => false, "msg" => "Создание новой секции не выполнено!");
		}
		return $res;
	}
	
	static function getViewData($db,$id=-1,$sections=""){
		$isAdmin 	= User::checkAccess("admin");
		$sections 	= $sections!=""?$sections:Section::get($db,"",$id);
		$result 	= "";
		$section 	= array();
		foreach($sections as $section){
			$author 			= Person::get($db,$section['author']);
			$section['author'] 	= Person::getFio($author);
			$comma 				= "";
			$buttons			= array();

//Парсинг кнопок
//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
			$reports_length	= Report::get("","",-1,"`state`<>-1 and `section`='".$section['id']."'",'count(*) as `count`');
			if($isAdmin&&$section['state']==0){
				$buttons['Редактировать'] 	= array("opt"=>array("icon"=>"pencil","action"=>"load","target"=>"dialog","text"=>false,"postData"=>array("form"=>true,"id"=>$section['id'])),"url"=>"section/edit");
				if($reports_length[0]['count']==0){
					$buttons['Удалить'] 	= array("opt"=>array("icon"=>"trash","text"=>false,"id"=>$section['id'],"name"=>$section['name']),"url"=>"section/delete","action"=>"deleteSection(opt,but)");
				}
			}else if($isAdmin&&$section['state']==-1){
					$buttons['Удалить'] 	= array("opt"=>array("icon"=>"trash","text"=>false,"id"=>$section['id'],"name"=>$section['name']),"url"=>"section/delete_final","action"=>"deleteSection(opt,but)");
			}
			
			if($id<0){
				$buttons['Показать'] 		= array("opt"=>array("icon1"=>"arrowthick-1-e","postData"=>array("id"=>$section['id']),"action"=>"load","target"=>"#tabs-id-section","hideEffect"=>"slide","showEffect"=>"slide"),"url"=>"section/list_");
			}else{
				$buttons['Назад'] 			= array("opt"=>array("icon"=>"arrowthick-1-w","action"=>"load","target"=>"#tabs-id-section","hideEffect"=>"slide","showEffect"=>"slide"),"url"=>"section/list_");
			}
			
			$section['buttons'] 			= Template::getButtons($buttons);
//*******************************************************************************************************************************************************************************************************************************************************************************************************************************************
			
			if($section['state']==-1){
				$section['state_class'] = ' b_r_2';
			}
			
			if($id==-1){
				$result.=Template::parse_('section/main.min',$section);
			}else{
				$reports 			= Report::get($db,"",-1," `section`='".$section['id']."'");
				$reports_view		= Report::getViewData($db,$reports);
				$section['section_reports'] = $reports_view!=""?$reports_view:"В данной секции нет докладов!";
				$result.=Template::parse_('section/main',$section);
			}
		}
		return $result;
	}
	
	static function getSectionSelect($db,$id=-1){
		$select = "<select name='section'><option value='-1'>Выберите секцию</option>";
		$sections = Section::get($db);
		foreach ($sections as $section) {
			$name = $section['name'];	
			if(strlen(utf8_decode($name))>30){
				$name = mb_substr($name,0,30,"UTF-8")."...";
			}
			$select.="<option id='section' value='".$section['id']."'".($section['id']==$id?" selected='selected'":"").">".$name."</option>";
		}
		return $select."</select>";
	}
	
	static function getTree($db){
		$select = "";
		$sections = Section::get($db);
		foreach ($sections as $section) {
			$name = $section['name'];	
			if(strlen(utf8_decode($name))>30){
				$name = mb_substr($name,0,30,"UTF-8")."...";
			}
			$reports = Report::get($db,"",-1," `section`='".$section['id']."'");
			$select.='<li class="closed"><span class="expandable">'.$name.'</span>';
			if(count($reports)>0){
				$select.="<ul>";
				foreach ($reports as $report) {
					$nm = $report['name'];
					if(strlen(utf8_decode($nm))>30){
						$nm=mb_substr($nm,0,30,"UTF-8");
					}
					$select.='<li><span>'.$nm.'</span></li>';
				}
				$select.="</ul>";
			}
			$select.="</li>";
		}
		return $select;
	}
}
?>